import paramiko
from pprint import pprint


# ssh连接函数
def ssh_connect(_host, _port, _username, _password):
    try:
        _ssh_fd = paramiko.SSHClient()
        _ssh_fd.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        _ssh_fd.connect(_host,
                        port=_port,
                        username=_username,
                        password=_password)
    except Exception as e:
        print('ssh {}@{}:{}'.format(_username, _host, e))
        exit()
    return _ssh_fd


# 执行命令函数
def ssh_exec_cmd(_ssh_fd, _cmd):
    return _ssh_fd.exec_command(_cmd)


# 关闭函数
def ssh_close(_ssh_fd):
    _ssh_fd.close()


if __name__ == '__main__':
    sshd = ssh_connect('192.168.1.105', 22, 'lnsix', 'xxxxxx')
    content = '''#!/bin/bash
read -p 'Enter your name:' name
echo "hello ${name},welcome to my program."
exit 0

for n in {1..255}
do
    host=192.168.1.${n}
    ping -c2 ${host} &>/dev/null
    if [ $? = 0 ];then
        echo "${host} is up"
    else:
        echo "${host} is down"
    fi
done
    '''
    with open('./read.sh', 'w+', encoding='utf-8') as sh:
        sh.write(content)
    # stdin, stdout, stderr = ssh_exec_cmd(sshd, 'ls -al |cut -d "." -f2')
    # stdin, stdout, stderr = ssh_exec_cmd(sshd, 'cat -n sh/read.sh|sed -n "2,5p"')
    stdin, stdout, stderr = ssh_exec_cmd(sshd, 'ifconfig eth0')
    # stdin, stdout, stderr = ssh_exec_cmd(
    #     sshd,
    #     'cat /home/lnsix/sh/read.sh|while read LINE;do echo ${LINE} ;done')
    err_list = stderr.readlines()
    if len(err_list) > 0:
        pprint('Error:{}'.format(err_list[0]))
        exit()
    for item in stdout.readlines():
        pprint(item)
    ssh_close(sshd)